<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\service\pay\PayService;
use app\service\api\OrderService;
use app\common\model\Channel;
use support\Request;
use app\common\model\Goods as GoodsModel;
use app\common\model\UserOrder as UserOrderModel;
use app\common\model\User as UserModel;
use app\common\model\GoodsOrder as GoodsOrderModel;

class Pay extends Base
{
    // 获取待支付的文章
    public function getGoodsDetail()
    {
        $id    = inputs('id/d', 0);
        $goods = GoodsModel::where('id', $id)->field('id,name,price,status,create_time,cate_id')->find();
        $this->success('获取成功', $goods);
    }

    public function getPayChannelData()
    {
        $where   = [];
        $where[] = ['status', '=', 1];

        if ($this->request->isMobile()) {
            $where[] = ['is_available', 'in', [0, 1]];
        } else {
            $where[] = ['is_available', 'in', [0, 2]];
        }
        $platform = Channel::where($where)->field(['id', 'paytype', 'show_name'])->order("sort desc")->select()->each(
            function ($item) {
                $item->setAttr('ico', $item->ico);
                $item->channel_id = $item->id;
                return true;
            }
        );
        return $platform->toArray();
    }

    // 获取支付方式 
    public function getPayChannel()
    {
        $data = $this->getPayChannelData();
        $this->success('获取成功', $data);
    }

    /**
     * 订单预检测
     * @param array $post 表单数据
     */
    private function checkBuyerStatus()
    {
        if ($this->user_id) {
            $user = UserModel::where('status', 1)->find($this->user_id);
            if (empty($user)) {
                throw new \Exception("买家不存在");
            }
            if ($user->is_freeze == 1) {
                throw new \Exception("买家已被禁止下单");
            }
        }
    }

    // 订单生成
    public function payOrder(OrderService $orderService)
    {
        // 订单预检测
        $this->checkBuyerStatus();

        $data = $orderService->createOrder([
            'goods_id' => inputs('goods_id/s', ''),
            'pid'      => inputs('pid/s', ''),
        ]);

        // 如果价格为0 则立即完成订单 todo
        if (empty($data['price'])) {
            throw new \Exception("免费商品，无需支付");
        }

        // 创建支付关联 如果存在用户
        if ($this->user_id) {
            $data['user_id']  = $this->user_id;
            $data['order_id'] = $data['id'];
            UserOrderModel::create($data);
        }


        $this->success("订单创建成功！请及时支付！", $data);
    }

    // 发起支付
    public function pay(PayService $payService)
    {
        $trade_no = request()->get('trade_no', '');

        try {
            $order = $payService->loadOrder($trade_no);
            switch ($order->status) {
                case 1:
                    return view("pay/pay", [
                        'msg' => "订单已支付！",
                    ]);

                case 2:
                    return view("pay/pay", [
                        'msg' => "订单已超时关闭！",
                    ]);

                case 3:
                    return view("pay/pay", [
                        'msg' => "订单已退款！",
                    ]);
            }
        } catch (\Exception $e) {
            return view("exception", [
                'msg' => $e->getMessage(),
            ]);
        }

        $total_price = round($order->total_price, 2);

        return $payService->pay($order, $trade_no, $total_price);
    }

    /**
     * 支付完成后手工点击返回
     */
    public function orderStatus()
    {
        $trade_no = request()->post('trade_no', '');
        $order    = GoodsOrderModel::where([
            'trade_no' => $trade_no,
        ])->find();
        if ($order->status === 2) {
            return $this->error('订单已超时关闭,请点击取消订单按钮');
        }
        if ($order->status != 1) {
            return $this->error('订单未支付');
        }
        return $this->success('订单已支付');
    }

    /** 
     * 买家手动点击关闭订单
     */
    public function orderClose()
    {
        $trade_no = request()->post('trade_no', '');
        $order    = GoodsOrderModel::where([
            'trade_no' => $trade_no,
        ])->find();
        if (empty($order)) {
            return $this->error('订单不存在');
        }
        if ($order->status === 2) {
            return $this->success('订单已关闭');
        }
        if ($order->status != 0) {
            return $this->error('订单不是未支付状态');
        }
        $order->status = 2;
        $order->save();
        return $this->success('操作成功');
    }


    /**
     * 公共 支付回调方法 | 所有支付的异步回调都走这里
     * @return void
     */
    public function notify(Request $request, $id = '')
    {
        $payService = new PayService();
        $request    = $request->all();
        return $payService->notify($request, $id);
    }
}
